<template>
  <div class="admin-visa">
    <div class="page-header">
      <h2>签证管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('visa_add')"
          type="primary" 
          @click="showAddDialog = true"
        >
          添加签证申请
        </el-button>
        
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索姓名/护照号/公司"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已出签" value="issued" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.nationality" placeholder="国籍" clearable @change="handleSearch">
            <el-option label="美国" value="US" />
            <el-option label="德国" value="DE" />
            <el-option label="日本" value="JP" />
            <el-option label="韩国" value="KR" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button @click="exportExcel">导出</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 签证申请列表 -->
    <el-table :data="visaList" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="company" label="公司名" width="150" />
      <el-table-column prop="name" label="联系人名字" width="120" />
      <el-table-column prop="position" label="职务" width="120" />
      <el-table-column prop="purpose" label="访问目的" min-width="200" />
      <el-table-column prop="email" label="联系人邮箱" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="申请时间" width="150" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button 
            v-if="hasPermission('visa_edit')"
            size="small" 
            type="primary" 
            @click="editVisa(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            v-if="hasPermission('visa_audit') && scope.row.status === 'pending'"
            size="small" 
            type="warning" 
            @click="auditVisa(scope.row)"
          >
            审核
          </el-button>
          <el-button 
            v-if="hasPermission('visa_delete')"
            size="small" 
            type="danger" 
            @click="deleteVisa(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑签证申请对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingVisa ? '编辑签证申请' : '添加签证申请'"
      width="800px"
    >
      <el-form :model="visaForm" :rules="visaRules" ref="visaFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名" prop="company">
              <el-input v-model="visaForm.company" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人名字" prop="name">
              <el-input v-model="visaForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="英文姓名" prop="nameEn">
              <el-input v-model="visaForm.nameEn" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护照号" prop="passportNo">
              <el-input v-model="visaForm.passportNo" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="国籍" prop="nationality">
              <el-input v-model="visaForm.nationality" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="visaForm.birthDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="visaForm.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="visaForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人邮箱" prop="email">
              <el-input v-model="visaForm.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="position">
              <el-input v-model="visaForm.position" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计入境日期" prop="entryDate">
              <el-date-picker
                v-model="visaForm.entryDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计出境日期" prop="exitDate">
              <el-date-picker
                v-model="visaForm.exitDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="访问目的" prop="purpose">
          <el-input v-model="visaForm.purpose" type="textarea" :rows="3" placeholder="请详细说明公司访问目的..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveVisa" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="showAuditDialog"
      title="审核签证申请"
      width="500px"
    >
      <el-form :model="auditForm" ref="auditFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="auditForm.auditComment" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAuditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="auditing">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { visaApi } from '@/api/admin'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminVisa',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const auditing = ref(false)
    const showAddDialog = ref(false)
    const showAuditDialog = ref(false)
    const editingVisa = ref(null)
    const auditingVisa = ref(null)
    const visaFormRef = ref(null)

    // 使用Excel导出hooks
    const { exportListData, columnWidthPresets, mapperPresets } = useExcelExport()
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      status: '',
      nationality: ''
    })
    
    // 签证申请表单
    const visaForm = reactive({
      name: '',
      nameEn: '',
      passportNo: '',
      nationality: '',
      birthDate: '',
      gender: 'male',
      phone: '',
      email: '',
      company: '',
      position: '',
      purpose: '',
      entryDate: '',
      exitDate: ''
    })
    
    // 审核表单
    const auditForm = reactive({
      status: 'approved',
      auditComment: ''
    })
    
    // 表单验证规则
    const visaRules = {
      company: [
        { required: true, message: '请输入公司名', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入联系人名字', trigger: 'blur' }
      ],
      position: [
        { required: true, message: '请输入职务', trigger: 'blur' }
      ],
      purpose: [
        { required: true, message: '请输入访问目的', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入联系人邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    }
    
    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })
    
    // 签证申请列表
    const visaList = ref([])
    
    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      // 开发阶段先返回true，确保所有功能可见
      if (userInfo.permissions?.includes('all') || userInfo.userType === 'admin') return true
      return userInfo.permissions?.includes(permission) || true // 临时返回true用于测试
    }
    
    // 获取状态样式
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        approved: 'success',
        rejected: 'danger',
        issued: 'info'
      }
      return types[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已拒绝',
        issued: '已出签'
      }
      return texts[status] || '未知'
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadVisa()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        keyword: '',
        status: '',
        nationality: ''
      })
      handleSearch()
    }
    
    // 加载签证申请数据
    const loadVisa = async () => {
      loading.value = true
      try {
        const params = {
          current: pagination.current,
          size: pagination.size,
          keyword: searchForm.keyword,
          status: searchForm.status,
          nationality: searchForm.nationality
        }
        
        const response = await visaApi.getVisaPage(params)
        if (response && response.data) {
          visaList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('加载签证申请数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    
    // 编辑签证申请
    const editVisa = (visa) => {
      editingVisa.value = visa
      Object.assign(visaForm, visa)
      showAddDialog.value = true
    }
    
    // 删除签证申请
    const deleteVisa = async (visa) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除 "${visa.name}" 的签证申请吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await visaApi.deleteVisa(visa.id)
        ElMessage.success('删除成功')
        loadVisa()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 审核签证申请
    const auditVisa = (visa) => {
      auditingVisa.value = visa
      auditForm.status = 'approved'
      auditForm.auditComment = ''
      showAuditDialog.value = true
    }
    
    // 提交审核
    const submitAudit = async () => {
      auditing.value = true
      try {
        const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
        const params = {
          id: auditingVisa.value.id,
          status: auditForm.status,
          auditComment: auditForm.auditComment,
          auditUser: userInfo.userCode || 'admin'
        }
        
        await visaApi.auditVisa(params)
        ElMessage.success('审核成功')
        showAuditDialog.value = false
        auditingVisa.value = null
        loadVisa()
      } catch (error) {
        ElMessage.error('审核失败')
      } finally {
        auditing.value = false
      }
    }
    
    // 保存签证申请
    const saveVisa = async () => {
      // 只验证5个必填字段
      const requiredFields = ['company', 'name', 'position', 'purpose', 'email']
      const missingFields = []
      
      for (const field of requiredFields) {
        if (!visaForm[field] || visaForm[field].trim() === '') {
          missingFields.push(field)
        }
      }
      
      if (missingFields.length > 0) {
        const fieldNames = {
          company: '公司名',
          name: '联系人名字', 
          position: '职务',
          purpose: '访问目的',
          email: '联系人邮箱'
        }
        const missingFieldNames = missingFields.map(field => fieldNames[field]).join('、')
        ElMessage.error(`请填写必填字段：${missingFieldNames}`)
        return
      }
      
      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(visaForm.email)) {
        ElMessage.error('请输入正确的邮箱格式')
        return
      }
      
      saving.value = true
      
      try {
        if (editingVisa.value) {
          await visaApi.updateVisa({ ...visaForm, id: editingVisa.value.id })
          ElMessage.success('签证申请更新成功')
        } else {
          await visaApi.addVisa(visaForm)
          ElMessage.success('签证申请添加成功')
        }
        
        showAddDialog.value = false
        editingVisa.value = null
        resetForm()
        loadVisa()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(visaForm, {
        name: '',
        nameEn: '',
        passportNo: '',
        nationality: '',
        birthDate: '',
        gender: 'male',
        phone: '',
        email: '',
        company: '',
        position: '',
        purpose: '',
        entryDate: '',
        exitDate: ''
      })
    }
    
    // 取消编辑
    const cancelEdit = () => {
      showAddDialog.value = false
      editingVisa.value = null
      resetForm()
    }
    
    
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadVisa()
    }
    
    const handleCurrentChange = (current) => {
      pagination.current = current
      loadVisa()
    }

    // 导出签证申请列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = {
          current: 1,
          size: 100000,
          keyword: searchForm.keyword,
          status: searchForm.status,
          nationality: searchForm.nationality
        }
        const response = await visaApi.getVisaPage(params)
        return response.data?.records || []
      }

      // 数据映射函数，对应签证申请表单中的字段
      const mapData = (item) => ({
        '公司名': mapperPresets.handleEmpty(item.company),
        '联系人名字': mapperPresets.handleEmpty(item.name),
        '英文姓名': mapperPresets.handleEmpty(item.nameEn),
        '护照号': mapperPresets.handleEmpty(item.passportNo),
        '国籍': mapperPresets.handleEmpty(item.nationality),
        '出生日期': mapperPresets.handleEmpty(item.birthDate),
        '性别': item.gender === 'male' ? '男' : item.gender === 'female' ? '女' : mapperPresets.handleEmpty(item.gender),
        '联系电话': mapperPresets.handleEmpty(item.phone),
        '联系人邮箱': mapperPresets.handleEmpty(item.email),
        '职务': mapperPresets.handleEmpty(item.position),
        '预计入境日期': mapperPresets.handleEmpty(item.entryDate),
        '预计出境日期': mapperPresets.handleEmpty(item.exitDate),
        '访问目的': mapperPresets.handleEmpty(item.purpose),
        '状态': getStatusText(item.status),
        '申请时间': mapperPresets.handleEmpty(item.createdTime)
      })

      // 自定义签证申请列表的列宽
      const visaColumnWidths = [
        { wch: 25 }, // 公司名
        { wch: 15 }, // 联系人名字
        { wch: 20 }, // 英文姓名
        { wch: 15 }, // 护照号
        { wch: 12 }, // 国籍
        { wch: 15 }, // 出生日期
        { wch: 8 },  // 性别
        { wch: 15 }, // 联系电话
        { wch: 25 }, // 联系人邮箱
        { wch: 15 }, // 职务
        { wch: 15 }, // 预计入境日期
        { wch: 15 }, // 预计出境日期
        { wch: 40 }, // 访问目的
        { wch: 12 }, // 状态
        { wch: 20 }  // 申请时间
      ]

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        '签证申请列表',
        visaColumnWidths,
        '签证申请列表'
      )
    }
    
    onMounted(() => {
      loadVisa()
    })
    
    return {
      loading,
      saving,
      auditing,
      showAddDialog,
      showAuditDialog,
      editingVisa,
      auditingVisa,
      searchForm,
      visaForm,
      auditForm,
      visaRules,
      pagination,
      visaList,
      hasPermission,
      getStatusType,
      getStatusText,
      handleSearch,
      resetSearch,
      editVisa,
      deleteVisa,
      auditVisa,
      submitAudit,
      saveVisa,
      cancelEdit,
      handleSizeChange,
      handleCurrentChange,
      exportExcel
    }
  }
}
</script>

<style scoped>
.admin-visa {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>